﻿using WebApp.BLL;
using WebApp.BLL.Manage;
using WebApp.Common;
using WebApp.Models;
using WebApp.ViewModels.Manage;
using WebApp.Web.Core.Auth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;

namespace WebApp.Web.Core
{
    public class UserAuthBLL
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        #region Login

        public static UserLoginResults DoLogin(UserLoginModel loginModel, string clientid, string urladdress, ref S_user user)
        {
            var userservice = new S_userService();
            var userroleservice = new S_user_roleService();
            var logservice = new S_user_logService();
            var errorlogservice = new S_user_loginerrorService();

            //var smstemplateservice = new S_sms_templateService();
            user = userservice.FindByUsername(loginModel.Username);

            if (user == null)
            {
                loginModel.Isneedcode = "1";
                loginModel.Errorlist.Add("用户名不存在！");
                //loginModel.Errorlist.Add(CSMSLang.Get("message_username_not_exits"));

                //记录登录日志
                logservice.addUserLog(enmOprtType.登陆失败, 0, loginModel.Username, "");
                //记录错误日志
                //errorlogservice.LoginError(loginModel.Clientid, 0, loginModel.Username, "用户名不存在！");
                errorlogservice.LoginError(loginModel.Clientid, 0, loginModel.Username, "用户名不存在！");

                return UserLoginResults.UserNotExist;
            }
            else if (Utils.NvStr(user.Password).ToUpper() != Utils.MD5Password(loginModel.Password).ToUpper())
            {
                //记录登录日志
                logservice.addUserLog(enmOprtType.登陆失败, user.Id, user.Username, "");
                //记录错误日志
                errorlogservice.LoginError(loginModel.Clientid, user.Id, loginModel.Username, "用户名或密码错误！");

                loginModel.Isneedcode = "1";
                loginModel.Errornum = errorlogservice.getErrorNumber(loginModel.Clientid, loginModel.Username);
                loginModel.Errorlist.Add("用户名或密码错误！");
                //loginModel.Errorlist.Add(CSMSLang.Get("message_username_or_password_error"));
                //if (loginModel.Errornum < 2)
                //{
                //    loginModel.Errorlist.Add("用户名或密码错误！");
                //}
                //else if (loginModel.Errornum >= 2 && loginModel.Errornum < 5)
                //{
                //    loginModel.Errorlist.Add("您已连续输错密码" + loginModel.Errornum + "次，超过5次后您的账号将被冻结！");
                //}
                //else
                //{
                //    loginModel.Errorlist.Add("您已连续输错密码5次以上，账号已被冻结！");

                //    //锁定用户
                //    user.Islocked = "1";
                //    this.CurrentRepository.Update(user);

                //    //记录锁定日志
                //    logservice.userLog(enmOprtType.锁定, user.Id, user.Username);
                //}

                return UserLoginResults.WrongPassword;
            }

            //清除错误次数
            errorlogservice.ClearErrorNumber(loginModel.Clientid);
            //记录成功日志
            logservice.addUserLog(enmOprtType.登陆成功, user.Id, user.Username, "");

            ////保存上次登录时间
            //user.Lastlogintime = DateTime.Now;
            //user.Lastloginip = Utils.GetClientIP();
            //user.Logintimes = user.Logintimes + 1;
            //user.Clientid = Guid.NewGuid().ToString().Replace("-", "");
            //userservice.Update(user);

            //用户角色
            int userid = user.Id;
            var userroles = userroleservice.SelectByUserid(user.Id).Select(p => p.Roleid).ToList();

            //保存Session
            SessionManage.User = new SessionUserModel(user);
            SessionManage.UserRoles = userroles;
            //SessionManage.ClientID = user.Clientid;
            //SessionManage.GlobalCustcode = user.Custcode;
            SessionManage.Language = "zh_cn";
            //缓存处理
            UserCache.InitUsreCache(SessionManage.User);
            //if (CommonStr.HasAuth("Study.Setting"))
            //{
            //    UserStudyCache.InitStudyCacheByCustcode(user.Custcode);
            //}
            //else
            //{
            //    UserStudyCache.InitUserStudyCache(user.Id);
            //}

            return UserLoginResults.Successful;
        }

        public static UserLoginResults Relogin(int userid)
        {
            var userservice = new S_userService();
            var userroleservice = new S_user_roleService();

            var user = userservice.Find(userid);

            ////保存上次登录时间
            //user.Lastlogintime = DateTime.Now;
            //user.Lastloginip = WebUtils.getIPAddress(System.Web.HttpContext.Current);
            //user.Logintimes = user.Logintimes;
            //user.Clientid = Guid.NewGuid().ToString().Replace("-", "");
            //userservice.Update(user);

            //用户角色
            var userroles = userroleservice.SelectByUserid(user.Id).Select(p => p.Roleid).ToList();
            //new S_user_roleRepository().Entities.Where(p => p.User_id == user.Id).Select(p => p.Roleid).ToList();

            //保存Session
            SessionManage.User = new SessionUserModel(user);
            SessionManage.UserRoles = userroles;
            //SessionManage.ClientID = user.Clientid;
            //SessionManage.GlobalCustcode = user.Custcode;

            //缓存处理
            UserCache.InitUsreCache(SessionManage.User);

            new S_user_logService().addUserLog(enmOprtType.重新登录, user.Id, user.Username, "");

            return UserLoginResults.Successful;
        }

        #endregion

        #region Logout

        public static void DoLogout()
        {
            try
            {
                //记录登出日志
                new S_user_logService().addUserLog(enmOprtType.登出, SessionManage.User.Id, SessionManage.User.Username, "");

                //清除用户缓存
                UserCache.ClearUserCache(SessionManage.User.Id);
                //UserStudyCache.ClearUserStudyCache(SessionManage.User.Id);

                //清除登录信息
                FormsAuthentication.SignOut();
                SessionManage.User = null;
                //SessionManage.ClientID = null;
                //SessionManage.GlobalCustcode = null;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        #endregion

        #region 判断用户是否拥有指定的角色

        /// <summary>
        /// 判断用户是否拥有指定的角色
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public static bool HasRole(string roleid)
        {
            if (string.IsNullOrEmpty(roleid)) throw new ArgumentNullException("roleid");

            if (SessionManage.UserRoles == null)
            {
                return false;
            }

            return SessionManage.UserRoles.Contains(roleid);
        }

        #endregion

        #region 根据ActionID判断用户是否有权限

        /// <summary>
        /// 根据ActionID判断用户是否有权限
        /// </summary>
        /// <param name="authcode"></param>
        /// <returns></returns>
        public static bool HasAuth(string authcode)
        {

            if (string.IsNullOrEmpty(authcode)) throw new ArgumentNullException("authcode");

            var checkresult = AuthorizeFilterAttribute.AuthorizeCore(authcode);

            return checkresult == AuthorizeResult.Success;
        }

        #endregion

    }
}
